package com.ilink.groundservice.controller.AiXNew;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ilink.groundservice.entity.VO.AiX.AiXToolResponse;
import com.ilink.groundservice.entity.VO.AiX.AiXToolUsageRecordResponse;
import com.ilink.groundservice.service.Tool.AiXToolService;
import com.ilink.groundservice.service.Tool.AiXToolUsageRecordService;
import com.ilink.ilinkapi.dto.ground.AiX.AiXToolFilterRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXToolInsertRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXToolUpdateRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXToolUsageRequest;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.ilinkcommon.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@Slf4j
@RequestMapping("/ground/aix/tool")
@RestController
@RequiredArgsConstructor
public class AiXToolController {

    private final AiXToolService toolService;
    private final AiXToolUsageRecordService usageRecordService;

    @MethodLog("获取工具列表")
    @GetMapping("/list")
    public R getToolList(@RequestParam(required = false) Long areaId,
                         @RequestParam(required = false) String tag,
                         @RequestParam(required = false) String keyword,
                         @RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer size) {
        try {
            AiXToolFilterRequest request = new AiXToolFilterRequest();
            request.setAreaId(areaId);
            request.setTag(tag);
            request.setKeyword(keyword);
            request.setPage(page);
            request.setSize(size);
            
            IPage<AiXToolResponse> responseIPage = toolService.getToolList(request);
            log.info("获取工具列表成功, total: {}", responseIPage.getTotal());
            return R.ok("工具列表获取成功", responseIPage);
        } catch (Exception e) {
            log.error("获取工具列表失败: {}", e.getMessage());
            return R.error("获取工具列表失败: " + e.getMessage());
        }
    }

    @MethodLog("获取工具详情")
    @GetMapping("/{toolId}")
    public R getToolDetail(@PathVariable Long toolId) {
        try {
            AiXToolResponse response = toolService.getToolById(toolId);
            log.info("获取工具详情成功, toolId: {}", toolId);
            return R.ok("工具详情获取成功", response);
        } catch (Exception e) {
            log.error("获取工具详情失败: {}", e.getMessage());
            return R.error("获取工具详情失败: " + e.getMessage());
        }
    }

    @MethodLog("启动工具")
    @PostMapping("/{toolId}/launch")
    public R launchTool(@PathVariable Long toolId,
                        @RequestBody(required = false) AiXToolUsageRequest request) {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            String inputConfig = request != null ? request.getInputConfig() : null;
            String sessionId = toolService.launchTool(toolId, userId, inputConfig);
            log.info("启动工具成功, toolId: {}, userId: {}, sessionId: {}", toolId, userId, sessionId);
            return R.ok("工具启动成功", sessionId);
        } catch (Exception e) {
            log.error("启动工具失败: {}", e.getMessage());
            return R.error("启动工具失败: " + e.getMessage());
        }
    }

    @MethodLog("停止工具")
    @PostMapping("/stop/{sessionId}")
    public R stopTool(@PathVariable String sessionId) {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            toolService.stopTool(sessionId, userId);
            log.info("停止工具成功, sessionId: {}, userId: {}", sessionId, userId);
            return R.ok("工具停止成功");
        } catch (Exception e) {
            log.error("停止工具失败: {}", e.getMessage());
            return R.error("停止工具失败: " + e.getMessage());
        }
    }

    @MethodLog("获取工具状态")
    @GetMapping("/status/{sessionId}")
    public R getToolStatus(@PathVariable String sessionId) {
        try {
            String status = toolService.getToolStatus(sessionId);
            log.info("获取工具状态成功, sessionId: {}, status: {}", sessionId, status);
            return R.ok("工具状态获取成功", status);
        } catch (Exception e) {
            log.error("获取工具状态失败: {}", e.getMessage());
            return R.error("获取工具状态失败: " + e.getMessage());
        }
    }

    @MethodLog("上传工具配置文件")
    @PostMapping("/{toolId}/upload-config")
    public R uploadToolConfig(@PathVariable Long toolId,
                              @RequestParam("file") MultipartFile file) {
        try {
            // TODO: 实现上传工具配置文件的逻辑
            log.info("上传工具配置文件, toolId: {}, fileName: {}", toolId, file.getOriginalFilename());
            return R.ok("工具配置文件上传成功");
        } catch (Exception e) {
            log.error("上传工具配置文件失败: {}", e.getMessage());
            return R.error("上传工具配置文件失败: " + e.getMessage());
        }
    }

    @MethodLog("下载工具结果")
    @GetMapping("/{toolId}/download-result")
    public R downloadToolResult(@PathVariable Long toolId,
                                @RequestParam String resultType) {
        try {
            // TODO: 实现下载工具结果的逻辑
            log.info("下载工具结果, toolId: {}, resultType: {}", toolId, resultType);
            return R.ok("工具结果下载成功");
        } catch (Exception e) {
            log.error("下载工具结果失败: {}", e.getMessage());
            return R.error("下载工具结果失败: " + e.getMessage());
        }
    }

    @MethodLog("获取工具使用历史")
    @GetMapping("/history")
    public R getToolHistory(@RequestParam(required = false) Long toolId,
                            @RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer size) {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            IPage<AiXToolUsageRecordResponse> responseIPage = usageRecordService.getUserUsageRecords(userId, toolId, page, size);
            log.info("获取工具使用历史成功, userId: {}, toolId: {}, total: {}", userId, toolId, responseIPage.getTotal());
            return R.ok("工具使用历史获取成功", responseIPage);
        } catch (Exception e) {
            log.error("获取工具使用历史失败: {}", e.getMessage());
            return R.error("获取工具使用历史失败: " + e.getMessage());
        }
    }

    @MethodLog("获取工具标签")
    @GetMapping("/categories/tags")
    public R getAllToolTags(@RequestParam Long areaId) {
        try {
            List<String> tags = toolService.getAllToolTags(areaId);
            log.info("获取工具标签成功, count: {}", tags.size());
            return R.ok("工具标签获取成功", tags);
        } catch (Exception e) {
            log.error("获取工具标签失败: {}", e.getMessage());
            return R.error("获取工具标签失败: " + e.getMessage());
        }
    }

    // 管理员接口：创建工具
    @MethodLog("创建工具")
    @PostMapping("/create")
    public R createTool(AiXToolInsertRequest request) {
        try {
            Long toolId = toolService.insertTool(request);
            log.info("创建工具成功, toolId: {}", toolId);
            return R.ok("工具创建成功", toolId);
        } catch (Exception e) {
            log.error("创建工具失败: {}", e.getMessage());
            return R.error("创建工具失败: " + e.getMessage());
        }
    }

    // 管理员接口：更新工具
    @MethodLog("更新工具")
    @PostMapping("/update")
    public R updateTool(@RequestBody AiXToolUpdateRequest request) {
        try {
            toolService.updateTool(request);
            log.info("更新工具成功, toolId: {}", request.getToolId());
            return R.ok("工具更新成功");
        } catch (Exception e) {
            log.error("更新工具失败: {}", e.getMessage());
            return R.error("更新工具失败: " + e.getMessage());
        }
    }

    // 管理员接口：删除工具
    @MethodLog("删除工具")
    @PostMapping("/delete/{toolId}")
    public R deleteTool(@PathVariable Long toolId) {
        try {
            toolService.deleteTool(toolId);
            log.info("删除工具成功, toolId: {}", toolId);
            return R.ok("工具删除成功");
        } catch (Exception e) {
            log.error("删除工具失败: {}", e.getMessage());
            return R.error("工具删除失败: " + e.getMessage());
        }
    }

    // 管理员接口：更新工具图标
    @MethodLog("更新工具图标")
    @PostMapping("/{toolId}/icon")
    public R updateToolIcon(@PathVariable Long toolId,
                           @RequestParam("file") MultipartFile file) {
        try {
            toolService.updateToolIcon(file, toolId);
            log.info("更新工具图标成功, toolId: {}", toolId);
            return R.ok("工具图标更新成功");
        } catch (Exception e) {
            log.error("更新工具图标失败: {}", e.getMessage());
            return R.error("更新工具图标失败: " + e.getMessage());
        }
    }

    @MethodLog("获取热门工具")
    @GetMapping("/popular")
    public R getPopularTools(@RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<AiXToolResponse> tools = toolService.getPopularTools(limit);
            log.info("获取热门工具成功, count: {}", tools.size());
            return R.ok("热门工具获取成功", tools);
        } catch (Exception e) {
            log.error("获取热门工具失败: {}", e.getMessage());
            return R.error("获取热门工具失败: " + e.getMessage());
        }
    }

    @MethodLog("获取工具最常用的8个标签")
    @GetMapping("/get_tool_tags")
    public R getToolTags(@RequestParam Long areaId) {
        try {
            List<String> tags = toolService.getToolTags(areaId);
            return R.ok("工具最常用的8个标签", tags);
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    @MethodLog("获取用户使用统计")
    @GetMapping("/statistics")
    public R getUserUsageStatistics() {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            Map<String, Object> statistics = usageRecordService.getUserUsageStatistics(userId);
            log.info("获取用户使用统计成功, userId: {}", userId);
            return R.ok("用户使用统计获取成功", statistics);
        } catch (Exception e) {
            log.error("获取用户使用统计失败: {}", e.getMessage());
            return R.error("获取用户使用统计失败: " + e.getMessage());
        }
    }

    @MethodLog("获取最近使用工具")
    @GetMapping("/recent")
    public R getRecentUsageRecords(@RequestParam(defaultValue = "10") Integer limit) {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            List<AiXToolUsageRecordResponse> records = usageRecordService.getRecentUsageRecords(userId, limit);
            log.info("获取最近使用工具成功, userId: {}, count: {}", userId, records.size());
            return R.ok("最近使用工具获取成功", records);
        } catch (Exception e) {
            log.error("获取最近使用工具失败: {}", e.getMessage());
            return R.error("获取最近使用工具失败: " + e.getMessage());
        }
    }

    @MethodLog("获取工具使用排行")
    @GetMapping("/ranking")
    public R getToolUsageRanking(@RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<Map<String, Object>> ranking = usageRecordService.getToolUsageRanking(limit);
            log.info("获取工具使用排行成功, count: {}", ranking.size());
            return R.ok("工具使用排行获取成功", ranking);
        } catch (Exception e) {
            log.error("获取工具使用排行失败: {}", e.getMessage());
            return R.error("获取工具使用排行失败: " + e.getMessage());
        }
    }
} 